﻿//  Copyright Joel de Guzman 2002-2004. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
//  or copy at http://www.boost.org/LICENSE_1_0.txt)
//  Hello World Example from the tutorial
//  [Joel de Guzman 10/9/2002]

#include <string>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/str.hpp>
#include <iconv.h>
using namespace boost::python;

bool iconv_ext(const char* src, char* dest, size_t inlen, size_t outlen, const char* tocode, const char* fromcode)
{
	char *inbuf = (char *)src;
	char *outbuf = dest;
	memset(outbuf, 0, outlen);
	iconv_t cd = iconv_open(tocode, fromcode);
	/* iconv接口会改变inbuf和outbuf，所以不能直接使用src和dest */
	size_t res = iconv(cd, &inbuf, &inlen, &outbuf, &outlen);
	iconv_close(cd);
	return (0 == res) ? true : false;
}

bool gbk2utf8(const char* src, char* dest, size_t inlen)
{
	return iconv_ext(src, dest, inlen, inlen * 4, "UTF-8", "GBK");
}

std::string gbk2utf8(const std::string & src)
{
	char dest[1024 * 1024];
	gbk2utf8(src.c_str(), dest, src.length());
	return dest;
}

bool utf82gbk(const char* src, char* dest, size_t inlen)
{
	return iconv_ext(src, dest, inlen, inlen, "GBK", "UTF-8");
}

bool utf82gbk(const std::string& src, char* dest)
{
	return utf82gbk(src.c_str(), dest, src.length());
}

std::string utf82gbk(const std::string& src)
{
	char dest[1024 * 1024];
	auto res = utf82gbk(src.c_str(), dest, src.length());
	return std::string(dest);
}

std::string greet_old(std::string name)
{	
	char buf[1024];
	utf82gbk(name, buf);
	std::string text{ "你好, " + utf82gbk(name) + "!" };

	gbk2utf8(text.c_str(),buf, text.length());
	return buf;
}


std::wstring greet(std::wstring name)
{
	return L"你好, " + name + L"!";
}


BOOST_PYTHON_MODULE(hello_ext)
{

	def("greet", greet);
}

